import 'dart:io' show Platform;
import 'package:flutter/cupertino.dart';
import 'package:macos_ui/macos_ui.dart';
import 'package:window_manager/window_manager.dart';

/// 颜色扩展方法
extension ColorExtension on Color {
  Color darken([double amount = 0.1]) {
    assert(amount >= 0 && amount <= 1);
    final hsl = HSLColor.fromColor(this);
    final hslDark = hsl.withLightness((hsl.lightness - amount).clamp(0.0, 1.0));
    return hslDark.toColor();
  }
}

/// 自定义窗口标题栏
class CustomWindowTitleBar extends StatefulWidget {
  final String title;
  final List<Widget>? actions;

  const CustomWindowTitleBar({
    super.key,
    required this.title,
    this.actions,
  });

  @override
  State<CustomWindowTitleBar> createState() => _CustomWindowTitleBarState();
}

class _CustomWindowTitleBarState extends State<CustomWindowTitleBar> with WindowListener {
  bool _isMaximized = false;

  @override
  void initState() {
    super.initState();
    windowManager.addListener(this);
    _checkMaximized();
  }

  @override
  void dispose() {
    windowManager.removeListener(this);
    super.dispose();
  }

  @override
  void onWindowMaximize() {
    setState(() {
      _isMaximized = true;
    });
  }

  @override
  void onWindowUnmaximize() {
    setState(() {
      _isMaximized = false;
    });
  }

  Future<void> _checkMaximized() async {
    final isMaximized = await windowManager.isMaximized();
    setState(() {
      _isMaximized = isMaximized;
    });
  }

  Future<void> _minimizeWindow() async {
    await windowManager.minimize();
  }

  Future<void> _maximizeOrRestore() async {
    if (_isMaximized) {
      await windowManager.unmaximize();
    } else {
      await windowManager.maximize();
    }
  }

  Future<void> _closeWindow() async {
    await windowManager.close();
  }

  @override
  Widget build(BuildContext context) {
    final isMacOS = Platform.isMacOS;

    return GestureDetector(
      onPanStart: (details) {
        windowManager.startDragging();
      },
      onDoubleTap: _maximizeOrRestore,
      child: Container(
        height: 50,
        decoration: BoxDecoration(
          color: MacosTheme.of(context).canvasColor,
          border: Border(
            bottom: BorderSide(
              color: MacosTheme.of(context).dividerColor,
            ),
          ),
        ),
        child: Row(
          children: [
            // macOS风格：左侧窗口控制按钮
            if (isMacOS) ...[
              const SizedBox(width: 12),
              _buildMacOSWindowButtons(),
              const SizedBox(width: 12),
            ],
            // Windows风格：左侧留空
            if (!isMacOS) const SizedBox(width: 16),
            
            // 标题
            Expanded(
              child: Text(
                widget.title,
                style: MacosTheme.of(context).typography.title2.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
              ),
            ),
            
            // 工具栏按钮
            if (widget.actions != null) ...widget.actions!,
            
            // Windows风格：右侧窗口控制按钮
            if (!isMacOS) ...[
              const SizedBox(width: 8),
              _buildWindowsWindowButtons(),
            ],
            
            // macOS风格：右侧留空
            if (isMacOS) const SizedBox(width: 16),
          ],
        ),
      ),
    );
  }

  Widget _buildMacOSWindowButtons() {
    return Row(
      children: [
        _MacOSWindowButton(
          color: MacosColors.systemRedColor,
          icon: CupertinoIcons.xmark,
          onPressed: _closeWindow,
        ),
        const SizedBox(width: 8),
        _MacOSWindowButton(
          color: MacosColors.systemYellowColor,
          icon: CupertinoIcons.minus,
          onPressed: _minimizeWindow,
        ),
        const SizedBox(width: 8),
        _MacOSWindowButton(
          color: MacosColors.systemGreenColor,
          icon: _isMaximized ? CupertinoIcons.arrow_down_right_arrow_up_left : CupertinoIcons.arrow_up_left_arrow_down_right,
          onPressed: _maximizeOrRestore,
        ),
      ],
    );
  }

  Widget _buildWindowsWindowButtons() {
    return Row(
      children: [
        _WindowsWindowButton(
          icon: CupertinoIcons.minus,
          onPressed: _minimizeWindow,
        ),
        _WindowsWindowButton(
          icon: _isMaximized ? CupertinoIcons.rectangle : CupertinoIcons.square,
          onPressed: _maximizeOrRestore,
        ),
        _WindowsWindowButton(
          icon: CupertinoIcons.xmark,
          onPressed: _closeWindow,
          isClose: true,
        ),
      ],
    );
  }
}

/// macOS风格的窗口按钮
class _MacOSWindowButton extends StatefulWidget {
  final Color color;
  final IconData icon;
  final VoidCallback onPressed;

  const _MacOSWindowButton({
    required this.color,
    required this.icon,
    required this.onPressed,
  });

  @override
  State<_MacOSWindowButton> createState() => _MacOSWindowButtonState();
}

class _MacOSWindowButtonState extends State<_MacOSWindowButton> {
  bool _isHovered = false;

  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      onEnter: (_) => setState(() => _isHovered = true),
      onExit: (_) => setState(() => _isHovered = false),
      child: GestureDetector(
        onTap: widget.onPressed,
        child: Container(
          width: 12,
          height: 12,
          decoration: BoxDecoration(
            color: widget.color,
            shape: BoxShape.circle,
            border: Border.all(
              color: widget.color.darken(0.2),
              width: 0.5,
            ),
          ),
          child: _isHovered
              ? Icon(
                  widget.icon,
                  size: 7,
                  color: widget.color.darken(0.4),
                )
              : null,
        ),
      ),
    );
  }
}

/// Windows风格的窗口按钮
class _WindowsWindowButton extends StatefulWidget {
  final IconData icon;
  final VoidCallback onPressed;
  final bool isClose;

  const _WindowsWindowButton({
    required this.icon,
    required this.onPressed,
    this.isClose = false,
  });

  @override
  State<_WindowsWindowButton> createState() => _WindowsWindowButtonState();
}

class _WindowsWindowButtonState extends State<_WindowsWindowButton> {
  bool _isHovered = false;

  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      onEnter: (_) => setState(() => _isHovered = true),
      onExit: (_) => setState(() => _isHovered = false),
      child: GestureDetector(
        onTap: widget.onPressed,
        child: Container(
          width: 46,
          height: 32,
          decoration: BoxDecoration(
            color: _isHovered
                ? (widget.isClose
                    ? MacosColors.systemRedColor
                    : MacosTheme.of(context).dividerColor.withOpacity(0.5))
                : null,
          ),
          child: Icon(
            widget.icon,
            size: 14,
            color: _isHovered && widget.isClose
                ? MacosColors.white
                : MacosTheme.of(context).typography.body.color,
          ),
        ),
      ),
    );
  }
}
